from django.shortcuts import render, redirect, HttpResponse
from django.http import HttpResponseRedirect
from django import http
from django.urls import reverse
# from pip._vendor.cachecontrol.serialize import Serializer
from ..index import models as index_models
from datetime import datetime
from django.core.mail import EmailMultiAlternatives

from apps.Userinfo.models import User, Authentication_Code
from django.contrib.auth import authenticate, logout, login
from django.views.generic import View
import re

from django.contrib.auth.hashers import make_password
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage
from django.contrib import messages

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from .forms import ContactForm

from django.core.mail import send_mail
from django.conf import settings

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

# django.contrib.auth.backends获取auth模块的验证和用户的信息
from django.contrib.auth.backends import ModelBackend

import json
import requests
import string
import random

class UC:
    def account(request):
        user = request.user
        if not user.is_authenticated:
            return redirect(reverse('login'))

        if request.method == 'POST':
            truename = request.POST.get('truename')
            phone = request.POST.get('phone')
            company_name = request.POST.get('company_name')
            company_address = request.POST.get('company_address')

            if len(truename) > 15:
                err = '本名は15文字を超えることはできません'
                return redirect(reverse('uc_account'))

            #phone_re = re.compile('^1\d{10}$')
            #if not re.match(phone_re, phone):
            #    err = '手机号格式不正确'
            #    return redirect(reverse('uc_account'))

            if len(company_name) > 100:
                err = '公司名不可超过100个字符'
                return redirect(reverse('uc_account'))

            if len(company_address) > 100:
                err = '会社名は 100 文字を超えることはできません'
                return redirect(reverse('uc_account'))
            user.truename = truename
            user.phone = phone
            user.company_name = company_name
            user.company_address = company_address
            user.save()

        now = datetime.now()
        vips = index_models.Vip.objects.filter(user=request.user, start_time__lte=now, end_time__gte=now).order_by(
            '-start_time')

        vip_all = index_models.Vip.objects.filter(user=request.user).order_by('-start_time')
        for v in vip_all:
            if v.start_time > datetime.now() or v.end_time < datetime.now():
                # v['over'] = True
                v.over = True

        webs = index_models.Web.objects.all()
        web_list = []
        for w in webs:
            w_list = []
            vv = index_models.Vip.objects.filter(user=request.user, web__name=w.name, start_time__lte=now,
                                                 end_time__gte=now)
            if not vv:
                # w['over'] = True
                w_list = [w, 0]
            else:
                w_list = [w, 1]
            web_list.append(w_list)

        is_all_vip_flag = True if index_models.Vip.objects.filter(user=request.user, web=None, start_time__lte=now,
                                                                  end_time__gte=now) else False

        return render(request, 'uc/uc-account.html',
                      {'vips': vips, 'vip_all': vip_all, 'is_all_vip_flag': is_all_vip_flag, 'web_list': web_list})

    def uc_verify(request):
        return render(request, 'uc/uc-verify.html')

    def uc_verify2(request):
        user = request.user
        if not user.is_authenticated:
            return redirect(reverse('login'))
        return render(request, 'uc/uc-verify2.html')

    def uc_verify3(request):
        return render(request, 'uc/uc-verify3.html')

    def uc_collection(request):
        user = request.user
        if not user.is_authenticated:
            return redirect(reverse('login'))

        collections = index_models.Collection.objects.filter(user=user).order_by('-id')

        paginator = Paginator(collections, 20)
        page = request.GET.get('page')
        try:
            collections = paginator.page(page)
            # todo: 注意捕获异常
        except PageNotAnInteger:
            # 如果请求的页数不是整数, 返回第一页。
            collections = paginator.page(1)
        except InvalidPage:
            # 如果请求的页数不存在, 重定向页面
            return HttpResponse('ページのコンテンツが見つかりませんでした')
        except EmptyPage:
            # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
            collections = paginator.page(paginator.num_pages)
        return render(request, 'uc/uc-collection.html', {'collections': collections})

    def uc_collect(request, flag, id):
        user = request.user
        if not user.is_authenticated:
            messages.error(request, "記事を収集するにはログインしてください")
            return redirect(reverse('login'))

        article = index_models.Article.objects.get(id=id)
        co = index_models.Collection.objects.filter(user=user, article=article)

        if co:
            co.delete()

            if flag == 'article_detail':
                return redirect(reverse("article_details", args=(id,)))
            else:
                return redirect(reverse("uc_collection"))

        else:
            co = index_models.Collection(user=user, article=article)
            co.save()
            return redirect(reverse("article_details", args=(id,)))

    def uc_history(request):
        user = request.user
        if not user.is_authenticated:
            return redirect(reverse('login'))

        histories = index_models.History.objects.filter(user=user).order_by('-created_time')

        paginator = Paginator(histories, 20)
        page = request.GET.get('page')
        try:
            histories = paginator.page(page)
            # todo: 注意捕获异常
        except PageNotAnInteger:
            # 如果请求的页数不是整数, 返回第一页。
            histories = paginator.page(1)
        except InvalidPage:
            # 如果请求的页数不存在, 重定向页面
            return HttpResponse('ページのコンテンツが見つかりませんでした')
        except EmptyPage:
            # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
            histories = paginator.page(paginator.num_pages)

        return render(request, 'uc/uc-history.html', {'histories': histories})

    def change_pwd(request):
        user = request.user
        if not user.is_authenticated:
            return redirect(reverse('login'))

        if request.POST:
            # user1 = User.objects.get(username='sasaky')
            # user1.password = make_password('00680zjhsi')
            # user1.save()
            if request.user.is_authenticated:
                pwd1 = request.POST['pwd1']
                pwd2 = request.POST['pwd2']
                if '' in [pwd1, pwd2]:
                    err = 'パスワードを空にすることはできません'
                    return render(request, 'uc/uc-verify2.html', {'err': err})
                elif pwd1 != pwd2:
                    err = 'パスワード入力に2回矛盾があります。もう一度確認してください'
                    return render(request, 'uc/uc-verify2.html', {'err': err})
                elif len(pwd1) < 8 or len(pwd1) > 16:
                    err = 'パスワードの長さは8~16文字ですので、再入力してください'
                    return render(request, 'uc/uc-verify2.html', {'err': err})
                else:
                    request.user.password = make_password(pwd1)
                    request.user.save()
                    return redirect('/uc-verify3')

        return render(request, 'uc/uc-verify2.html')

    def uc_contact_free(request):
        if request.method == 'POST':
            user = User.objects.get(email='it@helptechltd.com')
            email = request.POST.get('email')
            truename = request.POST.get('truename')
            phone = request.POST.get('phone')
            company_name = request.POST.get('company_name')
            company_address = request.POST.get('company_address')
            context = request.POST.get('context')
            check = request.POST.get('check')

            if '' in [email, truename, context]:
                err = '必須フィールドを空にすることはできません'
                return render(request, 'uc/uc-contact-free.html', {'err': err})

            # src_email = r'^([0-9a-zA-Z\_]{0,19})@([0-9a-zA-Z]{1,13})\.([com,cn,net]{1,3})$'
            src_email = r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$'
            m = re.match(src_email, email)
            if not m:
                err = 'メールボックスの形式が正しくありません'
                return render(request, 'uc/uc-contact-free.html', {'err': err})
            if len(truename) > 15:
                err = '本名は15文字を超えることはできません'
                return render(request, 'uc/uc-contact-free.html', {'err': err})

            #phone_re = re.compile('^1\d{10}$')
            #if not re.match(phone_re, phone):
            #    err = '手机号格式不正确'
            #    return render(request, 'uc/uc-contact-free.html', {'err': err})

            if len(company_name) > 100:
                err = '会社名は 100 文字を超えることはできません'
                return render(request, 'uc/uc-contact-free.html', {'err': err})

            if len(company_address) > 100:
                err = '会社の住所は 100 文字を超えることはできません'
                return render(request, 'uc/uc-contact-free.html', {'err': err})

            if len(context) > 1000:
                err = 'お問い合わせ内容は1000文字以内'
                return render(request, 'uc/uc-contact-free.html', {'err': err})

            if check != 'on':
                err = '同意してください'
                return render(request, 'uc/uc-contact-free.html', {'err': err})

            contact = index_models.Contact()
            contact.user = user
            contact.email = email
            contact.truename = truename
            contact.phone = phone
            contact.company_name = company_name
            contact.company_address = company_address
            contact.context = context
            contact.save()

            return render(request, 'uc/uc-contact-free.html', {'success': 'success'})

        return render(request, 'uc/uc-contact-free.html')
    def uc_contact(request):
        user = request.user
        if not user.is_authenticated:
            messages.error(request, "お問い合わせはログインしてください")
            return redirect(reverse('login'))
        else:
            if request.method == 'POST':
                email = request.POST.get('email')
                truename = request.POST.get('truename')
                phone = request.POST.get('phone')
                company_name = request.POST.get('company_name')
                company_address = request.POST.get('company_address')
                context = request.POST.get('context')
                check = request.POST.get('check')

                if '' in [email, truename, context]:
                    err = '必須フィールドを空にすることはできません'
                    return render(request, 'uc/uc-contact.html', {'err': err})

                # src_email = r'^([0-9a-zA-Z\_]{0,19})@([0-9a-zA-Z]{1,13})\.([com,cn,net]{1,3})$'
                src_email = r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$'
                m = re.match(src_email, email)
                if not m:
                    err = 'メールボックスの形式が正しくありません'
                    return render(request, 'uc/uc-contact.html', {'err': err})
                if len(truename) > 15:
                    err = '本名は15文字を超えることはできません'
                    return render(request, 'uc/uc-contact.html', {'err': err})

                #phone_re = re.compile('^1\d{10}$')
                #if not re.match(phone_re, phone):
                #    err = '手机号格式不正确'
                #    return render(request, 'uc/uc-contact.html', {'err': err})

                if len(company_name) > 100:
                    err = '会社名は 100 文字を超えることはできません'
                    return render(request, 'uc/uc-contact-free.html', {'err': err})

                if len(company_address) > 100:
                    err = '会社の住所は 100 文字を超えることはできません'
                    return render(request, 'uc/uc-contact-free.html', {'err': err})

                if len(context) > 1000:
                    err = 'お問い合わせ内容は1000文字以内'
                    return render(request, 'uc/uc-contact-free.html', {'err': err})

                if check != 'on':
                    err = '同意してください'
                    return render(request, 'uc/uc-contact-free.html', {'err': err})

                contact = index_models.Contact()
                contact.user = user
                contact.email = email
                contact.truename = truename
                contact.phone = phone
                contact.company_name = company_name
                contact.company_address = company_address
                contact.context = context
                contact.save()

                return render(request, 'uc/uc-contact.html', {'success': 'success'})
            return render(request, 'uc/uc-contact.html')


    def uc_vip(request):
        user = request.user
        if not user.is_authenticated:
            messages.error(request, "VIPメンバーシップを購入するには、まずログインしてください")
            return redirect(reverse('login'))
        else:
            if request.method == 'POST':
                email = request.POST.get('email')
                truename = request.POST.get('truename')
                phone = request.POST.get('phone')
                company_name = request.POST.get('company_name')
                company_address = request.POST.get('company_address')
                pay_type = request.POST.get('pay')

                check = request.POST.get('check')

                web0 = request.POST.get('v0')
                web1 = request.POST.get('v1')
                web2 = request.POST.get('v2')
                web3 = request.POST.get('v3')
                web4 = request.POST.get('v4')
                web5 = request.POST.get('v5')
                web6 = request.POST.get('v6')
                web7 = request.POST.get('v7')
                web8 = request.POST.get('v8')
                web9 = request.POST.get('v9')

                wl = [web0, web1, web2, web3, web4, web5, web6, web7, web8, web9]
                w_flag = False
                for w in wl:
                    if w:
                        w_flag = True

                if '' in [email, truename]:
                    err = '必須フィールドを空にすることはできません'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                src_email = r'^([0-9a-zA-Z\_]{0,19})@([0-9a-zA-Z]{1,13})\.([com,cn,net]{1,3})$'
                m = re.match(src_email, email)
                if not m:
                    err = 'メールボックスの形式が正しくありません'
                    return render(request, 'uc/uc-vip.html', {'err': err})
                if len(truename) > 15:
                    err = '本名は15文字を超えることはできません'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                #phone_re = re.compile('^1\d{10}$')
                #if not re.match(phone_re, phone):
                #    err = '手机号格式不正确'
                #    return render(request, 'uc/uc-vip.html', {'err': err})

                if len(company_name) > 100:
                    err = '会社名は 100 文字を超えることはできません'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                if len(company_address) > 100:
                    err = '会社の住所は 100 文字を超えることはできません'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                if check != 'on':
                    err = '同意してください'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                if not w_flag:
                    err = 'サイトを選択してください'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                if not pay_type:
                    err = 'お支払い方法を選択してください'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                # 判断是否重复提交
                o = index_models.Order.objects.filter(user=user, complete=False)
                if o:
                    err = '完了していない進行中の注文があります。繰り返し送信しないでください！'
                    return render(request, 'uc/uc-vip.html', {'err': err})

                price = 0
                if web0:
                    price += int(web0) * 800

                if web1:
                    price += int(web1) * 100

                if web2:
                    price += int(web2) * 200

                if web3:
                    price += int(web3) * 100

                if web4:
                    price += int(web4) * 200

                if web5:
                    price += int(web5) * 100

                if web6:
                    price += int(web6) * 100

                if web7:
                    price += int(web7) * 100

                if web8:
                    price += int(web8) * 200

                if web9:
                    price += int(web9) * 200

                print(price)

                order = index_models.Order()
                order.user = user
                order.email = email
                order.truename = truename
                order.phone = phone
                order.company_name = company_name
                order.company_address = company_address

                order.web0 = web0
                order.web1 = web1
                order.web2 = web2
                order.web3 = web3
                order.web4 = web4
                order.web5 = web5
                order.web6 = web6
                order.web7 = web7
                order.web8 = web8
                order.web9 = web9

                order.pay_type = pay_type
                order.price = price
                order.save()

                return render(request, 'uc/uc-vip.html', {'success': 'success'})

            return render(request, 'uc/uc-vip.html')


class Login:
    def login(request):
        if request.method == "POST":
            username = request.POST.get('username')
            password = request.POST.get('password')
            message = "ユーザー名とパスワードを入力してください！"
            if username and password:  # 确保用户名和密码都不为空
                username = username.strip()
                # user = User.objects.filter(username=username).first()
                user = authenticate(username=username, password=password)
                print('user', user)

                if user is not None:
                    login(request, user)
                    # return HttpResponseRedirect('index')
                    return HttpResponseRedirect(reverse("index"))
                else:
                    user_e_name = User.objects.filter(email=username).first()
                    user_e = None
                    if user_e_name:
                        user_e = authenticate(username=user_e_name.username, password=password)
                    if user_e:
                        login(request, user_e)
                        return HttpResponseRedirect(reverse("index"))
                    message = '間違ったユーザー名またはパスワードを入力した場合は、再入力してください！'
                    return render(request, "uc/login.html",
                                  {'message': message, 'user_name': username, 'password': password})

                # if not user:
                #     message = "用户名不存在！"
                #     return render(request, 'uc/login.html', {"message": message})
                #
                # if user.password == password:
                #     return redirect('index')
                # else:
                #     message = "密码不正确！"
            return render(request, 'uc/login.html', {"message": message})
        return render(request, 'uc/login.html')

    def logout(request):
        """
        退出登录
        :param request:
        :return:
        """
        logout(request)
        return HttpResponseRedirect('/')


class RegisterView(View):
    """注册"""

    def get(self, request):
        # 显示注册页面
        return render(request, 'uc/sign-in.html')

    def post(self, request):
        # 进行注册处理
        # 接收数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        email = request.POST.get('email')
        allow = request.POST.get('allow')

        # 进行数据校验
        if not all([username, password, email, password2]):
            # 数据不完整
            return render(request, 'uc/sign-in.html', {'message': '不完全なデータ'})

        # 检验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, 'uc/sign-in.html', {'message': 'メールボックスの形式が正しくありません'})

        if password != password2:
            # 数据不完整
            return render(request, 'uc/sign-in.html', {'message': '2 つのパスワード エントリが同じではありません'})

        if allow != 'on':
            return render(request, 'uc/sign-in.html', {'message': '同意してください'})

        # 校验用户是否重复
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # 用户名不存在
            user = None

        if user:
            return render(request, 'uc/sign-in.html', {'message': 'ユーザー名はすでに存在します。ユーザー名を置き換えてください'})

        # 校验Email是否重复
        try:
            email_chack = User.objects.get(email=email)
        except:
            # 用户名不存在
            email_chack = None

        if email_chack:
            return render(request, 'uc/sign-in.html', {'message': 'メールボックスは既に存在します。電子メール アドレスを置き換えてください'})

        # 校验手机号是否重复
        try:
            mobile_chack = User.objects.get(phone=mobile)
        except:
            # 用户名不存在
            mobile_chack = None

        if mobile_chack:
            return render(request, 'uc/sign-in.html', {'message': '携帯電話番号はすでに存在します。携帯電話を変更するか、直接ログインしてください'})

        # 进行业务处理：进行用户注册
        user = User.objects.create_user(username=username, email=email, phone=mobile, password=password, is_active=False)

        rv = RegisterView()
        active_res = rv.active_email_send(email)
        if active_res:
            return render(request, 'uc/register_success.html', {'email': email})
        else:
            return render(request, 'uc/sign-in.html',
                          {'message': 'アクティベーションメールの配信に失敗しました! メールの送受信がスムーズに行われているかご確認ください', 'email': email})

        # 发送激活链接，包含激活链接：http://127.0.0.1:8000/user/active/5
        # 激活链接中需要包含用户的身份信息，并要把身份信息进行加密
        # 激活链接格式: /user/active/用户身份加密后的信息 /user/active/token

        # 加密用户的身份信息，生成激活token
        # serializer = Serializer(settings.SECRET_KEY, 3600)
        # info = {'confirm': user.id}
        # token = serializer.dumps(info)  # bytes
        # token = token.decode('utf8')  # 解码, str
        #
        # # 发邮箱
        # subject = '天天生鲜欢迎信息'
        # message = ''
        # sender = settings.EMAIL_PROM  # 发送人
        # receiver = [email]
        # html_message = '<h1>%s, 欢迎您成为时视化工注册会员' \
        #                '</h1>请点击下面链接激活您的账户<br/>' \
        #                '<a href="http://127.0.0.1:8000/user/active/%s">' \
        #                'http://127.0.0.1:8000/user/active/%s' \
        #                '</a>' % (username, token, token)
        #
        # send_mail(subject, message, sender, receiver, html_message=html_message)

        # 找其他人帮助我们发送邮件 celery:异步执行任务
        # send_register_active_email.delay(email, username, token)

        # 返回应答,跳转首页
        # return redirect(reverse('index'))


# class CustomBackend(ModelBackend):
#     def authenticate(self, username=None, password=None, **kwargs):
#         try:
#             user = User.objects.get(Q(username=username) | Q(email=username))
#             if user.check_password(password):
#                 return user
#         except Exception as e:
#             return None

    def re_active_email_send(request,email):
        if email:
            rv = RegisterView()
            active_res = rv.active_email_send(email)
            if active_res:
                return render(request, 'uc/register_success.html', {'email': email})
            else:
                return render(request, 'uc/sign-in.html', {'message': 'アクティベーションメールの配信に失敗しました! メールの送受信がスムーズに行われているかご確認ください','email': email})
        else:
            return render(request, 'uc/register_fail.html', {'email': email})

    @staticmethod
    def active_email_send(email):
        user = User.objects.get(email=email)
        rv = RegisterView()
        verify_url = rv.generate_verify_email_url(user, type_='active')

        email_title = "ケミ・タイムズ　CHEMTIMES - アカウントの有効化"
        msg_html = f'''<!DOCTYPE html>
                        <html>
                        <meta charset="UTF-8">
                        <head>
                        <title>ケミ・タイムズ　CHEMTIMES - アカウントの有効化</title>
                        </head>
                        <body>
                        <div>尊敬するユーザー{user.username}様 :</div>

                                <p>ケミ・タイムズ　CHEMTIMESへのご登録ありがとうございます。完全な機能をご利用いただくには</p>
                                <p>30分以内に下記リンクをクリックしてアカウントを有効化してください: <a href = '{verify_url}'>{verify_url}</a></p>
                        </body>
                        </html>
                                    '''

        # 发送邮件
        send_status = EmailMultiAlternatives(email_title, msg_html, settings.DEFAULT_FROM_EMAIL, [email])
        send_status.content_subtype = "html"
        send_status.send()
        if not send_status:
            return False
        return True


    def generate_verify_email_url(self,user,type_):
        """
        生成邮箱验证链接
        :param user: 当前登录用户
        :return: verify_url
        """
        serializer = Serializer(settings.SECRET_KEY, expires_in=1800)
        data = {'user_id': user.uid, 'email': user.email}
        print(data)
        token = serializer.dumps(data).decode()
        # settings.EMAIL_VERIFY_URL是个固定的链接地址
        if type_ == 'change_pwd':
            verify_url = settings.EMAIL_VERIFY_URL + '/change_pwd?token=' + token
        else:
            verify_url = settings.EMAIL_VERIFY_URL + '/active_user?token=' + token
        return verify_url

    def check_verify_email_token(self,token):
        """
        验证token并提取user
        :param token: 用户信息签名后的结果
        :return: user, None
        """
        serializer = Serializer(settings.SECRET_KEY)
        try:
            data = serializer.loads(token)
        except BadData:
            return None
        else:
            user_id = data.get('user_id')
            email = data.get('email')
            try:
                user = User.objects.get(uid=user_id, email=email)
            except User.DoesNotExist:
                return None
            else:
                return user, user_id

    def forgot_pwd(request):
        # 显示忘记密码页面
        return render(request, 'uc/forgot-pwd.html')

    def send_pwd_mail(request):
        if request.method == "POST":
            return redirect(reverse('forgot_pwd'))
        # 显示忘记密码页面
        email = request.GET.get('email')
        if not email:
            return render(request, 'uc/forgot-pwd.html',{'message': 'ご登録のメールアドレスを入力してください'})
            # return redirect(reverse('forgot_pwd'),{'message': '请输入注册邮箱'})
        # 检验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, 'uc/forgot-pwd.html', {'message': 'メールボックスの形式が正しくありません'})

        user = User.objects.filter(email=email).first()
        if not user:
            return render(request, 'uc/forgot-pwd.html', {'message': 'このメールアドレスはこのウェブサイトに登録されていません！'})

        # 邮箱验证测试
        rv = RegisterView()
        verify_url = rv.generate_verify_email_url(user,type_='change_pwd')
        print(verify_url)

        email_title = "ケミ・タイムズ　CHEMTIMES-パスワード変更"
        msg_html = f'''<!DOCTYPE html>
                <html>
                <meta charset="UTF-8">
                <head>
                <title>ケミ・タイムズ　CHEMTIMES----パスワード変更</title>
                </head>
                <body>
                <div>ユーザー{user.username}：</div>
<p>30分以内に下記にリンクによるパスワードをご変更ください。：<a href='{verify_url}'>{verify_url}</a></p>
                </body>
                </html>
                            '''
        # 发送邮件
        send_status = EmailMultiAlternatives(email_title, msg_html, settings.DEFAULT_FROM_EMAIL, [email])
        send_status.content_subtype = "html"
        send_status.send()
        if not send_status:
            data = {
                'code': False
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)
        else:
            data = {
                'code': True
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)

    def sendsnscode(request):
        mobile = request.GET.get('mobile')
        if not mobile:
            data = {
                'code': False,
                'msg': '携帯電話番号を入力してください'
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)

        # 检查该手机号是否绑定账号并查出账号
        user = User.objects.filter(phone=mobile).first()
        if not user:
            data = {
                'code': False,
                'msg': 'ごめんなさい！ 携帯電話番号はこのサイトのアカウントにバインドされていません、携帯電話番号を変更するか、ホームページの右上隅をクリックして助けを求めてください！'
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)

        # 给mobile加区号
        mobile = mobile.strip()
        if mobile[0] == "1":
            pass
        elif mobile[0] == "0":
            mobile = '81' + mobile[1:]
        else:
            data = {
                'code': False,
                'msg': 'ごめんなさい！ 携帯電話番号の形式が正しくありませんので、確認して再度お問い合わせください！'
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)

        # 生成随机6位数验证码
        seeds = string.digits
        random_str = random.sample(seeds, k=6)
        code = "".join(random_str)

        print(code)
        host = 'https://gjsms.market.alicloudapi.com'
        path = '/sendgjSms'
        appcode = 'APPCODE 6fad7cf0bdcc4601a419f630d3532ce6'
        headers = {'Authorization': appcode}
        content = f'【Chemtimes】Your Chemtimes ID Verification Code is {code}'
        querys = f'content={content}&mobile={mobile}'

        url = host + path + '?' + querys

        r = requests.post(url, headers=headers)

        print(r.content)

        if r.content:
            res = json.loads(r.content)
            if res["list"][0]["result"] == 0:
                data = {
                    'code': True,
                }
                data_json = json.dumps(data)

                # 发送成功后把验证码存储到数据库
                AC = Authentication_Code()
                AC.user = user
                AC.code = code
                AC.save()

                return HttpResponse(data_json)

        data = {
            'code': False,
            'msg': '確認コードの送信に失敗しました。管理者にお問い合わせください'
        }
        data_json = json.dumps(data)
        return HttpResponse(data_json)

        # data = {
        #     'code': True,
        # }
        # data_json = json.dumps(data)
        # return HttpResponse(data_json)


    def checksnscode(request):
        mobile = request.GET.get('mobile')
        code = request.GET.get('code')
        if not mobile or not code:
            data = {
                'code': False,
                'msg': '電話番号または検証コードを入力してください'
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)

        # 检查该手机号是否绑定账号并查出账号
        user = User.objects.filter(phone=mobile).first()
        if not user:
            data = {
                'code': False,
                'msg': '申し訳ありませんが、その電話番号は当サイトのアカウントにバインドされていません。サイト管理者にお問い合わせください。'
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)

        # 查找数据库是否有相关数据
        AC = Authentication_Code.objects.filter(user=user, code=code).first()
        if AC:
            # 登录
            login(request, user)
            AC.delete()
            data = {
                'code': True
            }
            data_json = json.dumps(data)
            return HttpResponse(data_json)

        data = {
            'code': False,
            'msg': '認証に失敗しました。验证码を再取得するか、管理者にお問い合わせください。'
        }
        data_json = json.dumps(data)
        return HttpResponse(data_json)





    def link_change_pwd(request):
        token = request.GET.get('token')
        if token:
            rv = RegisterView()
            user,user_id = rv.check_verify_email_token(token)
            if user:
                login(request, user)
                return redirect(reverse('change_pwd'))
            else:
                return render(request, 'uc/forgot-pwd-fail.html', {'message': 'リンクが正しくないか、タイムアウトしたことを確認します'})
        else:
            return render(request, 'uc/forgot-pwd-fail.html', {'message': '検証リンクが正しくありません'})

    def active_user(request):
        token = request.GET.get('token')
        if token:
            rv = RegisterView()
            user,user_id = rv.check_verify_email_token(token)
            if user:
                login(request, user)
                user.is_active = True
                user.save()
                return render(request, 'uc/active_success.html')
            else:
                user = User.objects.get(uid=user_id)
                return render(request, 'uc/active_fail.html', {'message': 'アクティベーションリンクが正しくないか、タイムアウトしました','email':user.email})
        else:
            return render(request, 'uc/active_fail.html', {'message': 'アクティベーションリンクが正しくありません'})


    def test_email(request):
        subject = 'ケミ・タイムズ　CHEMTIMES　登録成功'
        message = 'test info'
        sender = settings.EMAIL_HOST_USER  # 发送人
        # receiver = ['zhefan_xu@yahoo.co.jp','xu@kanritsu.com']
        receiver = ['774365172@qq.com', 'konomitrading@163.com']
        # html_message = '<h1>%s, 欢迎您成为时视化工注册会员' \
        #                '</h1>请点击下面链接激活您的账户<br/>' \
        #                '< a href=" ">' \
        #                'http://127.0.0.1:8000/user/active/%s' \
        #                '</ a>' % ('username', '123', '123')
        html_message = '''<h1>%s, 時視化工の登録会員になっていただき、ありがとうございます。
</h1>下記リンクをクリックしてアカウントを有効化してください。<br/>
                       <a href="http://chemtimes.com/user/active">
                       http://chemtimes.com/user/active/
                       </a>'''

        s = send_mail(subject, message, sender, receiver, html_message=html_message)
        # print(s)
        print('the test information')
        return HttpResponse("success")